package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.dao.CategoryDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.pojo.Category;
import com.mozz.finally_work.utils.MybatisUtils;
import com.mozz.finally_work.utils.ParseMarkdown;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@WebServlet(name = "CategoryServlet", value = "/CategoryServlet")
public class CategoryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取userid*/
        String userId = request.getParameter("userId");
        String categoryId = request.getParameter("categoryId");
        if (userId.equals("")) {
            response.sendRedirect("login.jsp");
            return;
        }
        /*查询所有分类*/
        SqlSession session = MybatisUtils.getSession();
        CategoryDao categoryDao = session.getMapper(CategoryDao.class);
        List<Category> categories = categoryDao.queryALlCategoryByUserIdWithCount(userId);
        /*默认查询第一个分类*/
        BlogDao blogDao = session.getMapper(BlogDao.class);
        /*如果有categoryId，则查询对应的分类*/
        List<Blog> blogs = new ArrayList<>();
        if (categoryId!=null) {
            blogs = blogDao.queryBlogsByCategoryId(categoryId);
            request.setAttribute("selected",categoryId);
        }else{
            if (categories.size() > 0) {
                blogs = blogDao.queryBlogsByCategoryId(categories.get(0).getId());
            }
        }
        session.close();
        if (blogs.size() > 0) {
            for (Blog blog : blogs) {
                // 将 content由markdown转为html
                String parse = ParseMarkdown.parse(blog.getContent());
                blog.setContent(parse);
            }
        }
        request.setAttribute("categories", categories);
        request.setAttribute("blogs", blogs);
        // 请求转发
        request.getRequestDispatcher("categories.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
